package cn.tedu.charging.order.websocket;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint("/ws/server/{userId}")
public class WebSocketServer {

    private static ConcurrentHashMap<Integer, Session>
        sessionMap = new ConcurrentHashMap<>();


    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId){
        log.debug("用户{}连接了服务端",userId);
        sessionMap.put(userId,session);
        log.debug("用户:{}。上线，；连接成功:{}",userId,session);
    }

    @OnClose
    public void onClose(Session session,@PathParam("userId") Integer userId){
        log.debug("用户:{}下线了",userId);
        sessionMap.remove(userId);
        log.debug("用户:{}下线了，连接断开:{}",userId,session);
    }

    @OnMessage
    public void onMessage(String message,Session session){
        log.debug("用户:{}发送了消息:{}",session,message);
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        log.debug("用户:{}连接异常",session,throwable);
    }


    /**
     * 发送消息 给用户
     */
    public static void sendMessage(Integer userId,String message){
        Session session = sessionMap.get(userId);
        if(session!=null){
            session.getAsyncRemote().sendText(message);
        }else {
            log.debug("用户:{}未登录",userId);
        }
    }


}
